package com.jyu.apts.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.ItemDto;
import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.dto.TableDto;
import com.jyu.apts.dto.UserDto;
import com.jyu.apts.entity.Item;
import com.jyu.apts.entity.Organization;
import com.jyu.apts.entity.User;
import com.jyu.apts.service.ItemService;
import com.jyu.apts.service.UserService;
import com.jyu.apts.utils.AliyunOSSUtil;

@RestController
public class OrganizationItemController {

	@Autowired
	UserService userService;
	@Autowired
	ItemService itemService;
	
	@RequiresPermissions("organizationItem_html")
	@RequestMapping("/addOrganizationItem")
	public ResultDto addOrganizationItem(String name,MultipartFile image,String price) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Item item = new Item();
		item.setPrice(price);
		if(image!=null) {
			String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
			try {
				String objectName = AliyunOSSUtil.upload(image.getInputStream(), suffix);
				item.setImage("/oss/"+objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("上传失败", null, 2);
			}
		}
		item.setName(name);
		item.setOrganization(orgAdmin.getOrganization());
		itemService.save(item);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("organizationItem_html")
	@RequestMapping("/upOrganizationItem")
	public ResultDto upOrganizationItem(long id,String name,MultipartFile image,String price) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Item item = itemService.getOne(id);
		if(item == null)
			return new ResultDto("商品不存在!",null,2);
		if(item.getOrganization().getId()!=orgAdmin.getOrganization().getId())
			return new ResultDto("非本机构商品!",null,2);
		item.setPrice(price);
		if(image!=null) {
			String oldImg = item.getImage();
			if(oldImg!=null && oldImg.startsWith("/oss/")) {
				String oldObjectName =  oldImg.substring(5);
				AliyunOSSUtil.delete(oldObjectName);
			}
			String suffix = image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.') + 1);
			try {
				String objectName = AliyunOSSUtil.upload(image.getInputStream(), suffix);
				item.setImage("/oss/"+objectName);
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultDto("上传失败", null, 2);
			}
		}
		item.setName(name);
		itemService.save(item);
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("organizationItem_html")
	@RequestMapping("/delOrganizationItem")
	public ResultDto delUser(String ids) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		String[] idArray = ids.split(",");
		List<Long> l_ids = new ArrayList<Long>();
		for(String id : idArray) {
			l_ids.add(new Long(id));
		}
		List<Item> items = itemService.findAllById(l_ids);
		for(Item item : items) {
			if(item.getOrganization().getId()!=organization.getId())
				return new ResultDto("存在非本机构商品!",null,2);
		}
		itemService.delete(items);
		return new ResultDto("删除成功",null,0);
	}
	
	@RequiresPermissions("organizationItem_html")
	@RequestMapping("/getOrganizationItemPage")
	public TableDto<ItemDto> getOrganizationItemPage(Integer pageNumber,Integer pageSize,String search) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		Page<Item> pageResult = itemService.getItemPage(pageNumber, pageSize, organization.getId(), search);
		List<Item> items = pageResult.getContent();
		List<ItemDto> itemDtos = new ArrayList<ItemDto>();
		items.forEach(item->itemDtos.add(new ItemDto().convert(item)));
		return new TableDto<ItemDto>(itemDtos,pageResult.getTotalElements());
	}
	
	@RequiresAuthentication
	@RequestMapping("/getAllOrganizationItem")
	public List<ItemDto> getAllOrganizationItem() {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		List<Item> items = organization.getItems();
		List<ItemDto> itemDtos = new ArrayList<ItemDto>();
		items.forEach(item->itemDtos.add(new ItemDto().convert(item)));
		return itemDtos;
	}
	
	@RequiresPermissions("organizationItem_html")
	@RequestMapping("/organizationItem_html")
	public ModelAndView organizationItem_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/organizationItem.html");
		return mv;
	}
}
